using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using fads .Model;

namespace fads .DAL
{
	public class systemDAL
	{
		public int AddNew(system model)
		{
			object obj = SqlHelper.ExecuteScalar(
				"INSERT INTO system(sys_code,web_url,sys_name,description,icon_url,create_time,update_time) VALUES (@sys_code,@web_url,@sys_name,@description,@icon_url,@create_time,@update_time);SELECT @@identity"
				,new SqlParameter("@sys_code", model.sys_code)
				,new SqlParameter("@web_url", model.web_url)
				,new SqlParameter("@sys_name", model.sys_name)
				,new SqlParameter("@description", model.description)
				,new SqlParameter("@icon_url", model.icon_url)
				,new SqlParameter("@create_time", model.create_time)
				,new SqlParameter("@update_time", model.update_time)
			);
			return Convert.ToInt32(obj);
		}

		public bool Delete(int id)
		{
			int rows = SqlHelper.ExecuteNonQuery("DELETE FROM system WHERE id = @id", new SqlParameter("@id", id));
			return rows > 0;
		}

		public bool Update(system model)
		{
			string sql = "UPDATE system SET sys_code=@sys_code,web_url=@web_url,sys_name=@sys_name,description=@description,icon_url=@icon_url,create_time=@create_time,update_time=@update_time WHERE id=@id";
			int rows = SqlHelper.ExecuteNonQuery(sql
				, new SqlParameter("@id", model.id)
				, new SqlParameter("@sys_code", model.sys_code)
				, new SqlParameter("@web_url", model.web_url)
				, new SqlParameter("@sys_name", model.sys_name)
				, new SqlParameter("@description", model.description)
				, new SqlParameter("@icon_url", model.icon_url)
				, new SqlParameter("@create_time", model.create_time)
				, new SqlParameter("@update_time", model.update_time)
			);
			return rows > 0;
		}

		public system Get(int id)
		{
			DataTable dt = SqlHelper.ExecuteDataTable("SELECT * FROM system WHERE id=@id", new SqlParameter("@id", id));
			if (dt.Rows.Count > 1)
			{
				throw new Exception("more than 1 row was found");
			}
			if (dt.Rows.Count <= 0)
			{
				return null;
			}
			DataRow row = dt.Rows[0];
			system model = ToModel(row);
			return model;
		}

		private static system ToModel(DataRow row)
		{
			system model = new system();
			model.id = (object)row["id"];
			model.sys_code = (string)row["sys_code"];
			model.web_url = (string)row["web_url"];
			model.sys_name = (string)row["sys_name"];
			model.description = (string)row["description"];
			model.icon_url = (string)row["icon_url"];
			model.create_time = (object)row["create_time"];
			model.update_time = (object)row["update_time"];
			return model;
		}

		public IEnumerable<system> ListAll()
		{
			List<system> list = new List<system>();
			DataTable dt = SqlHelper.ExecuteDataTable("SELECT * FROM system");
			foreach (DataRow row in dt.Rows)
			{
				list.Add(ToModel(row));
			}
			return list;
		}
	}
}
